/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web.websocket;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author Marcos
 */
@ServerEndpoint("/chatws")
public class ChatWSEndpoint {

    private static Set<Session> participantes = Collections.synchronizedSet(new HashSet<Session>());

    @OnMessage
    public void onMessageChat(String message, Session session ) throws IOException, JSONException {

        JSONObject acoes = new JSONObject(message);
        
        acoes.put("idJogador", session.getId());
        acoes.put("autor", session.getId());

        for (Session peer : participantes) {
                peer.getBasicRemote().sendText(acoes.toString());
                
        }
    }

    @OnOpen
    public void onOpen(Session peer) {
        participantes.add(peer);
    }

    @OnClose
    public void onClose(Session peer) {
        participantes.remove(peer);
    }

}
